package service

import (
	"GinBlog/global"
	"GinBlog/models"
	"GinBlog/models/request"
	"errors"
)

type CommentService struct{}

func (u *CommentService) Create(comment *models.Comment) {
	global.DB.Create(&comment)
}

func (u *CommentService) Get(id uint) *models.Comment {
	comment := &models.Comment{}
	global.DB.First(&comment, id)
	return comment
}

func (u *CommentService) Update(comment *models.Comment, userid uint) error {
	c := u.Get(comment.ID)
	if c.ID == 0 {
		return errors.New("评论不存在")
	}
	if *c.UserID != userid {
		return errors.New("没有权限")
	}
	c.Content = comment.Content
	global.DB.Save(&c)
	return nil
}

func (u *CommentService) Delete(id uint, userid uint) error {
	c := u.Get(id)
	if c.ID == 0 {
		return errors.New("评论不存在")
	}
	if *c.UserID != userid {
		return errors.New("没有权限")
	}
	global.DB.Delete(&models.Comment{}, id)
	return nil
}

func (u *CommentService) List(info request.ListCommentRequest) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.DB.Model(&models.Comment{})
	var comments []*models.Comment

	if info.Content != "" {
		db = db.Where("content LIKE ?", "%"+info.Content+"%")
	}
	if info.UserId != 0 {
		db = db.Where("user_id = ?", info.UserId)
	}
	if info.PostId != 0 {
		db = db.Where("post_id = ?", info.PostId)
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("User").Find(&comments).Error
	return comments, total, err
}
